/**
 * 
 */
package sopia.sg;

import java.util.Calendar;

import sopia.cmm.CommonFunct;
import sopia.cmm.Constant;
import sopia.conn.AccountAdapter;
import sopia.conn.CategoryAdapter;
import sopia.conn.CustomerSpinnerAdapter;
import sopia.conn.DBAdapter;
import sopia.conn.ExpenseAdapter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author tatsu@gmail.com
 *
 */
public class G004Activity extends Activity {
	private TextView unit_expense;
	private String screenID;

	private Button addExpensive_button;
	//private Button datepicker_button;
	private EditText typeName_edit;
	private EditText amountExpensive_edit;
	private CategoryAdapter categoryAdapter;
	private ExpenseAdapter expenseAdapter;
	private AccountAdapter accAdapter;
	
	private Spinner categoryCombobox;
	private int myYear, myMonth, myDay;
	private String forMonth,forMonthToday;
//	private Button datePickerButton;
	//save value input
	private static String typeExpNameSave = Constant.EMPTY_STRING;
	private static String categoryExpSave;
	private static String amountExpSave = Constant.ZERO_VALUE;
	private static String forMonthSave = Constant.EMPTY_STRING;
	private static String plugID = Constant.EMPTY_STRING;
	private ArrayAdapter<CustomerSpinnerAdapter> adapter ;
	//
	private String valueCategory;
	static final int ID_DATEPICKER = 0;
	    private Button.OnClickListener datePickerButtonOnClickListener
	    = new Button.OnClickListener(){

	  @Override
	  public void onClick(View v) {
	   // TODO Auto-generated method stub
	   final Calendar c = Calendar.getInstance();
	   myYear = c.get(Calendar.YEAR);
	   myMonth = c.get(Calendar.MONTH);
	   myDay = c.get(Calendar.DAY_OF_MONTH);
	   showDialog(ID_DATEPICKER);
	  }
	   };
	 private DatePickerDialog.OnDateSetListener myDateSetListener
	  = new DatePickerDialog.OnDateSetListener(){
	   @Override
	   public void onDateSet(DatePicker view, int year, 
	     int monthOfYear, int dayOfMonth) {
	    forMonth = String.valueOf(monthOfYear + 1) + "/" + String.valueOf(year);
	    forMonthSave = forMonth;
//	    datePickerButton.setText(forMonth);
	   } 
	 };
	/**
	 * 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.g004_layout);
//		datePickerButton = (Button)findViewById(R.id.datepicker_button);
//        datePickerButton.setOnClickListener(datePickerButtonOnClickListener);
        init();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	  //Handle the back button
	  if (keyCode == KeyEvent.KEYCODE_BACK) {
			backToPreviousScreen();
			removeStaticValue();
	    return true;
	  }

	  return super.onKeyDown(keyCode, event);
	} 
   
	private void init() {
		unit_expense = (TextView) findViewById(R.id.unit_expense);
		unit_expense.setText(G001Activity.curUnitCurrency != null ? 
				G001Activity.curUnitCurrency : G003Activity.valueCurrencySelected);
	   //init time
	   final Calendar cl = Calendar.getInstance();
	   myYear = cl.get(Calendar.YEAR);
	   myMonth = cl.get(Calendar.MONTH);
	   forMonthToday = String.valueOf(myMonth + 1) + "/" + String.valueOf(myYear);
		if(Constant.EMPTY_STRING.equals(forMonthSave)){
			forMonthSave = forMonthToday;
		}
//	   datePickerButton.setText(forMonthToday);		   
		//init spinner category_combobox
		initCategorySpinner();
				
	    // screen ID call
		Intent receiveIntent = this.getIntent();
		this.screenID = receiveIntent.getStringExtra("ID");
		if(Constant.EMPTY_STRING.equals(this.plugID)){
			this.plugID = (receiveIntent.getStringExtra("PlugID") == null ? 
					Constant.EMPTY_STRING : receiveIntent.getStringExtra("PlugID"));
		}
		final Button forward_addCategory_button = (Button) findViewById(R.id.forward_addCategory_button);
		forward_addCategory_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(G004Activity.this, G007Activity.class);
				i.putExtra("ID", "G004");
				//save value before forward to screen
				typeExpNameSave = typeName_edit.getText().toString().trim();
				categoryExpSave = valueCategory;
				amountExpSave = amountExpensive_edit.getText().toString();
				//forMonthSave = datepicker_button.getText().toString();
				//
				startActivity(i);
				finish();
			}
		});
		// addExpensive_button 
		addExpensive_button = (Button) findViewById(R.id.addExpensive_button);
		typeName_edit = (EditText) findViewById(R.id.typeName_edit);
		valueCategory = Constant.EMPTY_STRING;
		categoryCombobox.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CustomerSpinnerAdapter category = (CustomerSpinnerAdapter) categoryCombobox.getItemAtPosition(position);
				valueCategory = category.getValue();
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		amountExpensive_edit = (EditText) findViewById(R.id.amountExpensive_edit);		
//		datepicker_button = (Button) findViewById(R.id.datepicker_button);		
		addExpensive_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(checkAmountAvailable()){
					insertTypeExpense(typeName_edit.getText().toString().trim(),G001Activity.curNameAccount
								 ,valueCategory,amountExpensive_edit.getText().toString());
				}else{
					showErrorMessage();
				}
			}
		});
		// set value old
		setOldValueScreen();
	}
	private void showErrorMessage(){
		if(CommonFunct.isNullOrEmpty(amountExpensive_edit.getText().toString())){
			Toast.makeText(this,"Please input value Amount" , Toast.LENGTH_LONG).show();
			amountExpensive_edit.selectAll();
			amountExpensive_edit.requestFocus();
			return;
		}else{
			double amount = Double.parseDouble(amountExpensive_edit.getText().toString());
			if(0 == amount){
					Toast.makeText(this,"Please input value Amount more than zero" , Toast.LENGTH_LONG).show();
					amountExpensive_edit.selectAll();
					amountExpensive_edit.requestFocus();
			}else {			
				String contentMessage =CommonFunct.join("With amount [",
						String.valueOf(Double.parseDouble(amountExpensive_edit.getText().toString())),
						" " , G001Activity.curUnitCurrency,
						"] that Account name [",
						G001Activity.curNameAccount,
						"] not enough to create this expense. \n Plz try again input value less than it.");
				Toast.makeText(this,contentMessage , Toast.LENGTH_LONG).show();
				amountExpensive_edit.selectAll();
				amountExpensive_edit.requestFocus();
				return;
			}
		}
	}
	private void setOldValueScreen() {
		typeName_edit.setText(typeExpNameSave);
		amountExpensive_edit.setText(amountExpSave);
	
		int spinnerPosition = CommonFunct.getIndexFromElement(adapter, categoryExpSave);
		//set the old according to value
		categoryCombobox.setSelection(spinnerPosition);
		
//		datepicker_button.setText(forMonthSave);
		
	}
	private void removeStaticValue(){
		typeExpNameSave = Constant.EMPTY_STRING;
		amountExpSave = Constant.ZERO_VALUE;
		forMonthSave = forMonthToday;
		categoryCombobox.setSelection(0);
	}
	private boolean checkAmountAvailable( ){
		String amountExp = amountExpensive_edit.getText().toString();
		try {
			if(CommonFunct.isNullOrEmpty(amountExp)){			
				return false;
			}
			double amountInput  = Double.parseDouble(amountExp);
			double amountUse = this.getAmountUsed();
			this.getAmountAccount();
			double totalAmount = G001Activity.curAmountAccount;
			if(totalAmount - amountUse >= amountInput){
				return true;
			}else{
				return false;
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	private void getAmountAccount() {
		if(CommonFunct.isNullOrEmpty(G001Activity.valueAccountSelected)){
			accAdapter = new AccountAdapter(this);	
			String amountAcc = accAdapter.getAmountCurrency(G003Activity.nameAccountAdded);		
			String[] amountCurrency = CommonFunct.removeHash(amountAcc);		
			G001Activity.curAmountAccount = Double.parseDouble(amountCurrency[0]);
			G001Activity.curNameAccount = G003Activity.nameAccountAdded;
			G001Activity.curUnitCurrency = G003Activity.valueCurrencySelected;
			accAdapter.close();
		}
	}



	private double getAmountUsed(){
		double amount = 0 ; 
		try {
			//get data
			expenseAdapter = new ExpenseAdapter(this);	
			Cursor cur = expenseAdapter.getAmountByAccount(G001Activity.curNameAccount);
			if (cur.moveToFirst()) {
		         do {
		        	 amount += cur.getDouble(0);
		         } while (cur.moveToNext());
		      }
		      if (cur != null && !cur.isClosed()) {
		    	  cur.close();
		      }
			expenseAdapter.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return amount;
	}

	protected void insertTypeExpense(String typeNameExp, String nameAccountExp,
						String nameCategoryExp, String amountExp) {
		try {
			expenseAdapter = new ExpenseAdapter(this);	
			expenseAdapter.beginTransaction();
			if(CommonFunct.isNullOrEmpty(typeNameExp)){
				typeNameExp = null;
				Toast.makeText(this,"Please input [Type Expense]!" , Toast.LENGTH_LONG).show();
				typeName_edit.setFocusable(true);
				return;
			}
			if(CommonFunct.isNullOrEmpty(amountExp)){
				Toast.makeText(this,"Please input value Amount" , Toast.LENGTH_LONG).show();
				amountExpensive_edit.selectAll();
				amountExpensive_edit.requestFocus();
				return;
			}else{
				double amount = Double.parseDouble(amountExp);
				if(0 == amount){
					Toast.makeText(this,"Please input value Amount more than zero" , Toast.LENGTH_LONG).show();
					amountExpensive_edit.selectAll();
					amountExpensive_edit.requestFocus();
					return;
				}
			}
			if(CommonFunct.isNullOrEmpty(nameCategoryExp)){
				Toast.makeText(this,"Please create Category" , Toast.LENGTH_LONG).show();
				categoryCombobox.requestFocus();
				return;
			}
			Long id = expenseAdapter.insertExpense(typeNameExp,nameAccountExp, nameCategoryExp, amountExp);
			//the row ID of the newly inserted row, or -1 if an error occurred 
			String contentMessage = "Type Expense [ "+ typeNameExp;
			if(id < 0){			
				contentMessage += "] really exist your database.";
				Toast.makeText(this,contentMessage , Toast.LENGTH_LONG).show();
				typeName_edit.selectAll();
			}else{
				contentMessage += "] was added.";				
				backToPreviousScreen();
				removeStaticValue();
				Toast.makeText(this, contentMessage , Toast.LENGTH_LONG).show();
			}
			expenseAdapter.setTransactionSuccessful();
		} catch (Exception e) {
			Log.e("insertTypeExpense", e.toString());
		}finally {
			expenseAdapter.endTransaction();
			expenseAdapter.close();
		}
		
	}



	private void initCategorySpinner() {
		try {
			categoryCombobox = (Spinner) findViewById(R.id.category_combobox);
			//get data
			categoryAdapter = new CategoryAdapter(this);	
			Cursor cur = categoryAdapter.getAllCategory();
			Log.d(String.valueOf(cur.getCount()), "TEST");
			categoryAdapter.close();
			//set data
			final CustomerSpinnerAdapter[] items = CommonFunct.getSpinnerAdapter(cur);
			adapter = new ArrayAdapter<CustomerSpinnerAdapter>(
					this, android.R.layout.simple_spinner_item, items);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			categoryCombobox.setAdapter(adapter);
			if (cur != null && !cur.isClosed()) {
		      cur.close();
		    }
		} catch (Exception e) {
			Log.e("initCategorySpinner", e.toString());
		}
		
	}
	private void backToPreviousScreen(){
		try {
			Intent i = null;
			if("G002".equals(screenID)){
				 i = new Intent(G004Activity.this, G002Activity.class);
			} else if ("G005".equals(screenID)){
				 i = new Intent(G004Activity.this, G005Activity.class);
			}else if ("G007".equals(screenID) && "G005".equals(this.plugID)){
				 this.plugID = Constant.EMPTY_STRING;
				 i = new Intent(G004Activity.this, G005Activity.class);
			}else {
				 i = new Intent(G004Activity.this, G002Activity.class);
			}
			startActivity(i);
			finish();
		} catch (Exception e) {
			Log.e("backToPreviousScreen", e.toString());
		}
	}
	


	@Override
	 protected Dialog onCreateDialog(int id) {
	  switch(id){
	   case ID_DATEPICKER:
	    return new DatePickerDialog(this,
	      myDateSetListener,
	      myYear, myMonth, myDay );
	   default:
	    return null;
	  }
	 }
}
